package ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.peng.auctionsystem.R;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import Widget.CustomToolBar;
import base.BaseActivity;
import butterknife.Bind;
import butterknife.ButterKnife;
import entity.CommondityListEntity;
import entity.DeleteEntity;
import entity.UserJoinCommodity;
import manager.ApiRequestManager;
import manager.RxSubscriber;
import ui.adapter.LotsDetailAdapter;
import ui.adapter.MyJoinCommodityAdapter;
import utils.Constants;
import utils.ToastUtil;

/**
 * 竞品页面（包括我的发布，流拍，已拍出我参与的等）
 */
public class LotDetailActivity extends BaseActivity implements CustomToolBar.OnToolBarClickListener, LotsDetailAdapter.ILotsCallback, AdapterView.OnItemClickListener {

    private List<CommondityListEntity.DataBean.RowsBean> commodityListData;

    private int page = 1;
    private int rows = 30;

    // 状态2表示拍卖中
    private String state = "2";

    private String commodityTitle;
    private String startTime;
    private String endTime;
    private String des;
    private int auctionGradient;
    private int currentPrice;
    private int commodityId;


    @Bind(R.id.custom_toolbar)
    CustomToolBar customToolbar;
    @Bind(R.id.lot_lv_lots)
    ListView lotLvLots;

    private int mDataType = 1;// 本页展示数据类型 1-我的发布 2-流拍 3-已拍出 4-我参与的
    private LotsDetailAdapter mAdapter;
    private int userId;
    private String picPath;
    private List<UserJoinCommodity.DataBean> data;
    private Date date;

    @Override
    public int getLayoutId() {
        return R.layout.activity_lot;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        mDataType = getIntent().getIntExtra("datatype", 1);

        SharedPreferences sPreferences = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        userId = sPreferences.getInt("userId", 0);

        initViews();

        loadData();

    }

    //获取各项竞品列表，根据参数设置状态
    private void loadData() {
        if (mDataType == 1) {
            mRxManager.add(
                    ApiRequestManager.getInstance().getMyPublishList(page, rows, userId)
                            .subscribe(new RxSubscriber<CommondityListEntity>(this) {
                                @Override
                                protected void _onNext(CommondityListEntity baseResult) {

                                    commodityListData = baseResult.getData().getRows();
                                    mAdapter = new LotsDetailAdapter(LotDetailActivity.this, mDataType, commodityListData);
                                    mAdapter.addCallback(LotDetailActivity.this);
                                    lotLvLots.setAdapter(mAdapter);
                                }

                                @Override
                                protected void _onError(String message) {
                                    ToastUtil.showShort("登陆失败");
                                }
                            }));
        } else if (mDataType == 2) {
            state = "2";
            getCommodityList(state);
        } else if (mDataType == 3) {
            state = "3";
            getCommodityList(state);
        } else if (mDataType == 4) {
            mRxManager.add(
                    ApiRequestManager.getInstance().userJoinCommodity(userId+"")
                            .subscribe(new RxSubscriber<UserJoinCommodity>(this) {
                                @Override
                                protected void _onNext(UserJoinCommodity baseResult) {
                                    data = baseResult.getData();
                                    MyJoinCommodityAdapter mAdapter = new MyJoinCommodityAdapter(LotDetailActivity.this, mDataType, data);
                                    lotLvLots.setAdapter(mAdapter);
                                }

                                @Override
                                protected void _onError(String message) {
                                    ToastUtil.showShort("登陆失败");
                                }
                            }));
        }
    }

    public void getCommodityList(String state) {
        mRxManager.add(
                ApiRequestManager.getInstance().getCommodityStateList(page, rows, userId, state)
                        .subscribe(new RxSubscriber<CommondityListEntity>(this) {
                            @Override
                            protected void _onNext(CommondityListEntity baseResult) {
                                commodityListData = baseResult.getData().getRows();
                                mAdapter = new LotsDetailAdapter(LotDetailActivity.this, mDataType, commodityListData);
                                mAdapter.addCallback(LotDetailActivity.this);
                                lotLvLots.setAdapter(mAdapter);
                            }

                            @Override
                            protected void _onError(String message) {
                                ToastUtil.showShort("登陆失败");
                            }
                        }));
    }

    private void initViews() {
        customToolbar.findTextView(R.id.left_tv).setVisibility(View.GONE);
        customToolbar.findImageView(R.id.left_iv).setVisibility(View.VISIBLE);
        customToolbar.findTextView(R.id.right_tv_main).setVisibility(View.GONE);
        customToolbar.findTextView(R.id.right_tv_sub).setVisibility(View.GONE);
        String title = "";
        switch (mDataType) {
            case Constants.MY_LOT:
                title = "我的发布";
                break;
            case Constants.PASS_IN_LOT:
                title = "流拍竞品";
                break;
            case Constants.PASS_OUT_LOT:
                title = "已拍出";
                break;
            case Constants.MY_JOIN_LOT:
                title = "参与竞品";
                break;
        }

        customToolbar.findTextView(R.id.center_tv).setText(title);
        customToolbar.setOnCustomToolBarClickListener(this);
        lotLvLots.setOnItemClickListener(this);
        //mAdapter.updateAdapter(commodityListData);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        if (mDataType == Constants.MY_JOIN_LOT) {
            commodityTitle = data.get(position).getTitle();
            startTime = data.get(position).getStartTime();
            endTime = data.get(position).getEndTime();
            auctionGradient = data.get(position).getAuctionGradient();
            des = data.get(position).getRemark();
            currentPrice = data.get(position).getNowPrice();
            commodityId = data.get(position).getId();
            picPath = data.get(position).getImagePath();
        } else {
            commodityTitle = commodityListData.get(position).getTitle();
            startTime = commodityListData.get(position).getStartTime();
            endTime = commodityListData.get(position).getEndTime();
            auctionGradient = commodityListData.get(position).getAuctionGradient();
            des = commodityListData.get(position).getRemark();
            currentPrice = commodityListData.get(position).getNowPrice();
            commodityId = commodityListData.get(position).getId();
            picPath = commodityListData.get(position).getImagePath();
        }

        Bundle data = new Bundle();
        data.putString("picPath",picPath);
        data.putString("commodityTitle", commodityTitle);
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            date = format1.parse(startTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        data.putString("startTime",format2.format(date));
        try {
            date = format1.parse(endTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        data.putString("endTime", format2.format(date));
//        data.putString("startTime", startTime);
//        data.putString("endTime", endTime);
        data.putInt("auctionGradient", auctionGradient);
        data.putString("des", des);
        data.putInt("currentPrice", currentPrice);
        data.putInt("commodityId", commodityId);

        Intent intent = new Intent(this, ProductDetailActivity.class);
        intent.putExtra("data", data);
        intent.putExtras(data);

        intent.putExtra("datatype", mDataType);
        startActivity(intent);
    }

    @Override
    public void onLotEdit(int position) {
        commodityTitle = commodityListData.get(position).getTitle();
        startTime = commodityListData.get(position).getStartTime();
        endTime = commodityListData.get(position).getEndTime();
        auctionGradient = commodityListData.get(position).getAuctionGradient();
        des = commodityListData.get(position).getRemark();
        currentPrice = commodityListData.get(position).getNowPrice();
        commodityId = commodityListData.get(position).getId();
        picPath = commodityListData.get(position).getImagePath();

        Intent intent = new Intent(this, PublishActivity.class);
        intent.putExtra("isPublish", 0);
        intent.putExtra("id",commodityListData.get(position).getId());
        Bundle data = new Bundle();
        data.putString("picPath",picPath);
        data.putString("commodityTitle", commodityTitle);
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            date = format1.parse(startTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        data.putString("startTime",format2.format(date));
        try {
            date = format1.parse(endTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        data.putString("endTime", format2.format(date));
//        data.putString("startTime", startTime);
//        data.putString("endTime", endTime);
        data.putInt("auctionGradient", auctionGradient);
        data.putString("des", des);
        data.putInt("currentPrice", currentPrice);
        data.putInt("commodityId", commodityId);

        intent.putExtra("data", data);
        intent.putExtras(data);

        intent.putExtra("datatype", mDataType);
        startActivity(intent);
    }

    @Override
    public void onLotDelete(int position) {
        // TODO 删除某竞品

        int id = commodityListData.get(position).getId();

        mRxManager.add(
                ApiRequestManager.getInstance().deleteCommodity(id)
                        .subscribe(new RxSubscriber<DeleteEntity>(this) {
                            @Override
                            protected void _onNext(DeleteEntity baseResult) {
                                loadData();
                            }

                            @Override
                            protected void _onError(String message) {
                                ToastUtil.showShort("登陆失败");
                            }
                        }));

    }

    @Override
    public void onTitleLeftClick(View view) {
        finish();
    }

    @Override
    public void onTitleCenterClick(View view) {

    }

    @Override
    public void onTitleRightClick(View view) {

    }

    @Override
    public void onTitleRightSubClick(View view) {

    }

}
